package com.scujj.filter;

import com.alibaba.fastjson.JSONObject;
import com.scujj.util.CheckToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;


@Component
public class LoginGlobalFilter implements GlobalFilter, Ordered {
    private final String[] skipAuthUrls = {"api-user/user/login/", "api-user/user/register", "api-user/user/checkCode/", "api-static/","api-webSocket/"};
    @Autowired
    private CheckToken checkToken;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求url地址
        String url = exchange.getRequest().getURI().getPath();
        //跳过不需要验证的路径
        if (isSkipUrl(url)) {
            return chain.filter(exchange);
        }
        //从请求头中取得token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        if (!checkToken.check(token)) {
            return createErrorResponseObj(exchange);
        } else {
            return chain.filter(exchange);
        }
    }


    private Mono<Void> createErrorResponseObj(ServerWebExchange exchange) {
        ServerHttpResponse response =
                exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", -1);
        map.put("message", "用户未登录");
        byte[] responseByte = JSONObject.toJSONString(map).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(responseByte);
        return response.writeWith(Flux.just(buffer));
    }

    private boolean isSkipUrl(String url) {
        for (String skipAuthUrl : skipAuthUrls) {
            if (url.contains(skipAuthUrl)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}